package com.wpre.booksystem.controller;

import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-12-09
 * Time: 16:31
 */

@RestController()
public class UploadController {

    @PostMapping("/upload")
    public String upload(MultipartFile file) {
        if (file.isEmpty()) {
            return "图片为空";
        }
        String originalFilename = file.getOriginalFilename();//原图片名
        if (originalFilename == null) {
            return "";
        }
        String ext = "." + originalFilename.split("\\.");
        String uuid = UUID.randomUUID().toString().replace("", "-");
        String fileName = uuid + ext;
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        String pre = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath()
                + "\\src\\main\\resources\\static\\images\\";
        //上传图片
        String path = pre + fileName;
        try {
            file.transferTo(new File(path));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return path;
    }
}
